package com.fourhats.services.util;

import java.util.ArrayList;
import java.util.List;

public class Page <T>{

	private List<?> elements;
	
	private int pageIndex;
	
	private int pageSize;
	
	private int totalItems;
	
	private int totalPages;

	public Page() {
		this.elements = new ArrayList<T>();
	}
	
	public List<?> getElements() {
		return elements;
	}

	public void setElements(List<?> ts) {
		this.elements = ts;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalItems() {
		return totalItems;
	}

	public void setTotalItems(int totalItems) {
		this.totalItems = totalItems;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	
	public static Page<?> create(List<?> elements, int pageIndex, int pageSize) {
		Page<?> p = new Page<Object>();
		
		p.setElements(getSublist(pageIndex, pageSize, elements));
		p.setPageIndex(pageIndex);
		p.setPageSize(pageSize);
		p.setTotalItems(elements.size());
		
		int quantity = p.getTotalItems() / pageSize;
		p.setTotalPages(p.getTotalItems() % pageSize != 0 ? quantity + 1 : quantity);
		
		return p;
	}
	
	public static Page<?> create(List<?> elements, int pageIndex, int pageSize, int totalItems) {
		Page<?> p = new Page<Object>();
		
		p.setElements(elements);
		p.setPageIndex(pageIndex);
		p.setPageSize(pageSize);
		p.setTotalItems(totalItems);
		
		int quantity = p.getTotalItems() / pageSize;
		p.setTotalPages(p.getTotalItems() % pageSize != 0 ? quantity + 1 : quantity);
		
		return p;
	}
	
	private static List<?> getSublist(int pageIndex, int pageSize, List<?> elements) {
		int firstElement = (pageIndex - 1) * pageSize;
		int lastElement = pageIndex * pageSize > elements.size() ? elements.size() : pageIndex * pageSize;
		return elements.subList(firstElement, lastElement);
	}
}
